package com.htstar.ovms.device.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.util.concurrent.ListenableFuture;
import com.htstar.ovms.admin.api.feign.EtpInfoFeign;
import com.htstar.ovms.admin.api.feign.SysFileFeign;
import com.htstar.ovms.admin.api.vo.EtpInfoSVo;
import com.htstar.ovms.common.core.constant.SecurityConstants;
import com.htstar.ovms.common.core.i18n.MsgCode;
import com.htstar.ovms.common.core.util.OvmDateUtil;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.log.annotation.SysLog;
import com.htstar.ovms.common.minio.service.MinioTemplate;
import com.htstar.ovms.common.security.util.SecurityUtils;
import com.htstar.ovms.device.api.constant.ExportRecordConstant;
import com.htstar.ovms.device.api.dto.CarSecurityAlarmDTO;
import com.htstar.ovms.device.api.dto.CarViolationsDTO;
import com.htstar.ovms.device.api.entity.CarViolations;
import com.htstar.ovms.device.api.entity.ExportRecord;
import com.htstar.ovms.device.api.vo.CarViolationsVO;
import com.htstar.ovms.device.api.vo.DeviceAlarmVO;
import com.htstar.ovms.device.handle.event.AlarmExcelExportEvent;
import com.htstar.ovms.device.handle.event.ViolationsExcelExportEvent;
import com.htstar.ovms.device.service.CarViolationsService;
import com.htstar.ovms.device.service.ExportRecordService;
import com.htstar.ovms.device.util.PoiExcelUtil;
import io.minio.ObjectStat;
import io.netty.util.concurrent.Future;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.manager.HTMLManagerServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @author htxk
 * @date 2020-10-29 18:39:11
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/carviolations")
@Api(value = "carviolations", tags = "违规车辆管理/Violation vehicle management")
public class CarViolationsController {

    private final CarViolationsService carViolationsService;
    private final ExportRecordService exportRecordService;
    private final SysFileFeign sysFileFeign;
    private final EtpInfoFeign etpInfoFeign;

    private final ApplicationEventPublisher publisher;


    /**
     * 分页查询
     *
     * @return
     */
    @ApiOperation(value = "分页查询/Paging query", notes = "分页查询")
    @PostMapping("/page")
    public R<Page<CarViolationsVO>> getCarViolationsPage(@RequestBody CarViolationsDTO carViolationsDTO) {
//        Page<CarViolationsVO> rs = carViolationsService.getCarViolationsPageForMultiEtpId(carViolationsDTO);
//        return R.ok(rs);
        return R.ok(carViolationsService.getAllCarViolationsPage(carViolationsDTO));
    }
//
//    /**
//     * 导出
//     *
//     * @return
//     */
//    @ApiOperation(value = "导出违规记录", notes = "导出违规记录")
//    @PostMapping("/exportCarViolation")
//    public void exportCarViolationsVO(@RequestBody CarViolationsDTO carViolationsDTO) {
//        String exportName = null;
//        ExportRecord exportRecord = new ExportRecord();
//        BigExcelWriter writer = null;
//        try {
//         /*   导出中.....*/
//            exportName  = "违规消息"+new String(URLEncoder.encode(
//                    "违规消息" + OvmDateUtil.getCstNow().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
//                    , "UTF-8").getBytes("UTF-8"), "ISO8859-1") + ".xlsx";
//           exportRecord.setEtpId(carViolationsDTO.getEtpId());
//            exportRecord.setUserId(carViolationsDTO.getUserId());
//            exportRecord.setExportName(exportName);
//            exportRecord.setExportType(ExportRecordConstant.VIOLATION_INFORMATION);
//            exportRecord.setExportStatus(ExportRecordConstant.EXPORTING);
//            exportRecord.setExportUrl("e:/"+exportName);
//            exportRecordService.save(exportRecord);
//            List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(carViolationsDTO.getEtpId());
//            currentAndParents1.forEach(etpInfoSVo -> {
//                carViolationsDTO.setEtpIds(etpInfoSVo.getIds());
//            });
//           List<CarViolationsVO> carViolationsVOS = carViolationsService.exportCarViolationsVO(carViolationsDTO);
//            if (CollectionUtils.isEmpty(carViolationsVOS)) {
//                return;
//            }
//            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);//设置子线程共享
//            writer = ExcelUtil.getBigWriter("e:/"+exportName);
//            writer.renameSheet("违规车辆");
//            List<Map<String, Object>> rows = new ArrayList<>();
//        for (CarViolationsVO carViolationsVO : carViolationsVOS) {
//            Map<String, Object> row = new LinkedHashMap<>();
//            row.put("车牌号码", carViolationsVO.getLicCode() == null ? "" : carViolationsVO.getLicCode());
//            row.put("企业", carViolationsVO.getEtpName() == null ? "" : carViolationsVO.getEtpName());
//            row.put("设备号", carViolationsVO.getDeviceSn() == null ? "" : carViolationsVO.getDeviceSn());
//            row.put("发生时间", carViolationsVO.getStaTime() == null ? "" : carViolationsVO.getStaTime());
//            row.put("违规发生地址", carViolationsVO.getStaAddr() == null ? "" : carViolationsVO.getStaAddr());
//            row.put("违规结束地址", carViolationsVO.getEndAddr() == null ? "" : carViolationsVO.getEndAddr());
//            rows.add(row);
//        }
//            OutputStream out = null;
//            writer.write(rows,true);
//        } catch (Exception e) {
//            /*   导出失败.....*/
//            e.printStackTrace();
//            exportRecord.setExportStatus(ExportRecordConstant.EXPORT_FAILED);
//            exportRecordService.updateById(exportRecord);
//            return;
//        }
//        try {
//            publisher.publishEvent(new ViolationsExcelExportEvent(this, carViolationsDTO));
//        } catch (Exception e) {
//            log.error("发布警情报表导出错误");
//        }
//        /*   导出成功.....*/
//            writer.close();
//        //IoUtil.close(out);
//            exportRecord.setExportStatus(ExportRecordConstant.EXPORT_SUCCEEDED);
//            exportRecordService.updateById(exportRecord);
////        try {
////            InputStream stream = new FileInputStream("e:/违规消息%E8%BF%9D%E8%A7%84%E6%B6%88%E6%81%AF2021-01-13+10%3A22%3A14.xlsx");
////            sysFileFeign.uploads("ovms", "e:/违规消息%E8%BF%9D%E8%A7%84%E6%B6%88%E6%81%AF2021-01-13+10%3A22%3A14.xlsx",stream);
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//            return;
//    }
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + new String(URLEncoder.encode(
//                    "定位信息" + OvmDateUtil.getCstNowDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
//                    , "UTF-8").getBytes("UTF-8"), "ISO8859-1") + ".xlsx");
//            out = response.getOutputStream();
//            writer.flush(out, true);


    /**
     * 通过id查询
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询/Query by id", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(carViolationsService.getById(id));
    }


    /**
     * 新增
     *
     * @param carViolations
     * @return R
     */
    @ApiOperation(value = "新增/Add", notes = "新增")
    @SysLog("新增")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin_carviolations_add')")
    public R save(@RequestBody CarViolations carViolations) {
        return R.ok(carViolationsService.save(carViolations));
    }

    /**
     * 修改
     *
     * @param carViolations
     * @return R
     */
    @ApiOperation(value = "修改/modify", notes = "修改")
    @SysLog("修改")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin_carviolations_edit')")
    public R updateById(@RequestBody CarViolations carViolations) {
        return R.ok(carViolationsService.updateById(carViolations));
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除/Delete by id", notes = "通过id删除")
    @SysLog("通过id删除")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('admin_carviolations_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(carViolationsService.removeById(id));
    }



    /**
     * 导出
     *
     * @return
     */
    @ApiOperation(value = "大量导出违规车辆行程数据报表/Export a large number of reports on the trip data of illegal vehicles", notes = "大量导出报警数据报表")
    @PostMapping("/exportCarViolations")
    public R hugeExcelExportAlarm(@RequestBody CarViolationsDTO carViolationsDTO) {
        Integer etpId = SecurityUtils.getUser().getEtpId();
        if (carViolationsDTO.getEtpId() == null) {
            carViolationsDTO.setEtpId(etpId);
        }
        List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(carViolationsDTO.getEtpId());
        currentAndParents1.forEach(etpInfoSVo -> {
            carViolationsDTO.setEtpIds(etpInfoSVo.getIds());
        });
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);//设置子线程共享
        //save export record
        ExportRecord exportRecord = new ExportRecord();
        exportRecord.setEtpId(etpId);
        exportRecord.setExportType(ExportRecordConstant.VIOLATION_INFORMATION);
        exportRecord.setExportStatus(ExportRecordConstant.EXPORTING);
        exportRecord.setUserId(SecurityUtils.getUser().getId());
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
        String fileName = "违规消息_" + SecurityUtils.getUser().getId() + "_" + dtf2.format(LocalDateTime.now());
        exportRecord.setExportName(fileName);
        exportRecordService.save(exportRecord);
        carViolationsDTO.setExportId(exportRecord.getId());
        carViolationsDTO.setUserId(SecurityUtils.getUser().getId());
        carViolationsDTO.setFileName(fileName);
        try {
            publisher.publishEvent(new ViolationsExcelExportEvent(this, carViolationsDTO));
        } catch (Exception e) {
            exportRecord.setExportStatus(ExportRecordConstant.EXPORT_FAILED);
            exportRecordService.updateById(exportRecord);
            log.error("发布违规报表导出错误");
        }

        return R.ok(MsgCode.EXPORTING.msg());
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return R
     */

    public static String getResponse(String serverUrl) {
        //用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while((line = in.readLine()) != null){
                result.append(line);
            }
            in.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();

    }
    public  static void  calculateDistance() {

        //使用的位置是经纬度用逗号隔开的Double longitude, Double latitude, Double longitude2, Double latitude2
//        String startLonLat = longitude+","+latitude;
//        String endLonLat = longitude2+","+latitude2;
        Long result = new Long(0);
        //restKey指的是高德的key，需要注册
        String queryUrl = "https://restapi.amap.com/v3/direction/driving?" +
                "key=c2db02aadd57337cde925cc389a7506a&origin=116.481028,39.989643&destination=116.465302,40.004717";
        String queryResult = getResponse(queryUrl);
        JSONObject jo = JSONObject.parseObject(queryResult);
        System.out.println(jo.toJSONString());
        JSONArray ja = jo.getJSONArray("route");
        JSONObject a = JSONObject.parseObject(ja.get(0).toString());
        result = Long.parseLong(a.getString("distance"));
        double doubleValue = result.doubleValue()/1000;
        System.out.println("两地相距："+doubleValue+"KM");
    }

//    public static void main(String[] args) {
//        CarViolationsController.calculateDistance();
//    }
}
